﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ProgNetComponents.Tools
{
    /// <summary>
    /// Tools for file operations
    /// </summary>
    public static class FileTools
    {
        /// <summary>
        /// Gets encoding of a file
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static Encoding GetFileEncoding(string fileName)
        {
            Encoding e = null;
            using (var r = new StreamReader(fileName, detectEncodingFromByteOrderMarks: true))
            {
                e = r.CurrentEncoding;
            }
            return e;
        }
        public delegate void FileCopyProgress(long fileLength, long bytesCopied);

        public static void CopyFile(string SourceFilePath, string DestFilePath, FileCopyProgress progressReporter, int bufferSize = 1024*1024)
        {
            byte[] buffer = new byte[bufferSize];

            using (FileStream source = new FileStream(SourceFilePath, FileMode.Open, FileAccess.Read))
            {
                long fileLength = source.Length;
                using (FileStream dest = new FileStream(DestFilePath, FileMode.CreateNew, FileAccess.Write))
                {
                    long bytesCopied = 0;
                    int currentBlockSize = 0;

                    while ((currentBlockSize = source.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        bytesCopied += currentBlockSize;
                        dest.Write(buffer, 0, currentBlockSize);
                        if (progressReporter != null)
                            progressReporter(fileLength, bytesCopied);
                    }
                }
            }
        }
    }
}
